package com.astn.bks;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.astn.bks.util.DateUtils;
import com.astn.bks.util.WebserviceUtils;
import com.astn.entity.booking.QuoteCountry;
import com.astn.entity.booking.QuoteRegion;
import com.astn.entity.booking.QuoteRequest;
import com.astn.entity.booking.QuoteState;
import com.astn.entity.booking.QuoteTown;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.test.suitebuilder.TestSuiteBuilder.FailedToCreateTests;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

public class PostRequest extends Activity {
	private Button btnPostRequest;
	private Button btnExit;
	private EditText txtChildren;
	private EditText txtAdult;
	private EditText txtFrom;
	private EditText txtTo;
	private Spinner spnCountry;
	private Spinner spnState;
	// private Spinner spnRegion;
	private Spinner spnTown;
	private Date from;
	private int mYear, mMonth, mDay;
	private String message;
	private final int FROM_DATE_INPUT_DIALOG = 87;
	private final int TO_DATE_INPUT_DIALOG = 88;
	private final int FAIL_REPORT = 89;
	private Date pickedFromDate;
	private Date pickedToDate;
	private List<QuoteCountry> lstCountry = new Vector<QuoteCountry>();
	private QuoteCountry selectedCountry;
	private List<QuoteState> lstState = new Vector<QuoteState>();
	private QuoteState selectedState;
	// private List<QuoteRegion> lstRegion = new Vector<QuoteRegion>();
	// private QuoteRegion selectedRegion;
	private List<QuoteTown> lstTown = new Vector<QuoteTown>();
	private QuoteTown selectedTown;

	private QuoteRequest currentRequest;
	private DatePickerDialog.OnDateSetListener fromDatePickerListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			Calendar cal = GregorianCalendar.getInstance();
			cal.set(year, monthOfYear, dayOfMonth);
			pickedFromDate = cal.getTime();
			txtFrom.setText(pickedFromDate.toString());
		}
	};
	private DatePickerDialog.OnDateSetListener toDatePickerListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			Calendar cal = GregorianCalendar.getInstance();
			cal.set(year, monthOfYear, dayOfMonth);
			pickedToDate = cal.getTime();
			txtTo.setText(pickedToDate.toString());
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.postrequest);
		// btnPostRequest = (Button) findViewById(R.id.btnPostRequest);
		txtAdult = (EditText) findViewById(R.id.txtAdult);
		txtChildren = (EditText) findViewById(R.id.txtChildren);
		txtFrom = (EditText) findViewById(R.id.txtFrom);
		txtTo = (EditText) findViewById(R.id.txtTo);
		spnCountry = (Spinner) findViewById(R.id.spnCountry);
		spnState = (Spinner) findViewById(R.id.spnState);
		// spnRegion = (Spinner) findViewById(R.id.spnRegion);
		spnTown = (Spinner) findViewById(R.id.spnTown);
		btnPostRequest = (Button) findViewById(R.id.btnPostRequest);
		btnExit = (Button) findViewById(R.id.btnExit);
		// Get list of country from Joomla server
		String response = (String) WebserviceUtils.call("com_xmlrpc",
				"getAllCountry", null);
		if (response != null) {
			JSONArray arr = (JSONArray) JSONValue.parse(response);
			if (arr != null) {
				for (int i = 0; i < arr.size(); i++) {
					JSONObject obj = (JSONObject) arr.get(i);
					QuoteCountry tc = new QuoteCountry();
					try {
						int id = Integer.parseInt(obj.get("id").toString());
						String countrycode = (String) obj.get("countrycode");
						String countryname = (String) obj.get("countryname");
						tc.setId(id);
						tc.setCountrycode(countrycode);
						tc.setCountryname(countryname);
						lstCountry.add(tc);
					} catch (Exception e) {
					}
				}
			}
		}
		ArrayAdapter<QuoteCountry> adap = new ArrayAdapter<QuoteCountry>(this,
				android.R.layout.simple_spinner_item, lstCountry);
		adap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spnCountry.setAdapter(adap);

		// Action when select a country
		spnCountry.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				selectedCountry = (QuoteCountry) arg0.getItemAtPosition(arg2);
				Map<String, Object> para = new HashMap<String, Object>();
				para.put("COUNTRYID",
						selectedCountry != null ? selectedCountry.getId() : "");
				String response = (String) WebserviceUtils.call("com_xmlrpc",
						"getStateOfCountry", para);
				lstState = new Vector<QuoteState>();
				if (response != null) {
					JSONArray arr = (JSONArray) JSONValue.parse(response);
					if (arr != null) {
						for (int i = 0; i < arr.size(); i++) {
							JSONObject obj = (JSONObject) arr.get(i);
							QuoteState st = new QuoteState();
							try {
								int id = Integer.parseInt((String) obj
										.get("id"));
								int regionId = 0;
								try {
									regionId = Integer.parseInt((String) obj
											.get("regionid"));

								} catch (Exception e) {
									// TODO: handle exception
								}
								String statecode = (String) obj
										.get("statecode");
								int statenumber = 0;
								try {
									statenumber = Integer.parseInt((String) obj
											.get("statenumber"));
								} catch (Exception e) {
									// TODO: handle exception
								}
								String statename = (String) obj
										.get("statename");
								int countryid = Integer.parseInt((String) obj
										.get("countryid"));
								st.setId(id);
								st.setRegionid(regionId);
								st.setStateCode(statecode);
								st.setStatenumber(statenumber);
								st.setStatename(statename);
								lstState.add(st);
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					}
					QuoteState nullState = new QuoteState();
					nullState.setCountryid(0);
					nullState.setId(0);
					nullState.setRegionid(0);
					nullState.setStateCode("");
					nullState.setStatename("None");
					nullState.setStatenumber(0);
					lstState.add(0, nullState);
					ArrayAdapter<QuoteState> adap = new ArrayAdapter<QuoteState>(
							PostRequest.this,
							android.R.layout.simple_spinner_item, lstState);
					adap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					spnState.setAdapter(adap);

				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});

		spnState.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				selectedState = (QuoteState) arg0.getItemAtPosition(arg2);
				lstTown = new Vector<QuoteTown>();
				Map<String, Object> para = new HashMap<String, Object>();
				para.put("STATEID",
						selectedState != null ? selectedState.getId() : "");
				String response = (String) WebserviceUtils.call("com_xmlrpc",
						"getTownOfState", para);
				if (response != null) {
					JSONArray arr = (JSONArray) JSONValue.parse(response);
					if (arr != null) {
						for (int i = 0; i < arr.size(); i++) {
							JSONObject obj = (JSONObject) arr.get(i);
							QuoteTown st = new QuoteTown();
							try {
								int id = Integer.parseInt((String) obj
										.get("id"));
								int regionid = Integer.parseInt((String) obj
										.get("regionid"));
								int countryid = Integer.parseInt((String) obj
										.get("countryid"));
								String citynumber = (String) obj
										.get("citynumber");
								String citycode = (String) obj.get("citycode");
								String cityname = (String) obj.get("cityname");
								int stateid = Integer.parseInt((String) obj
										.get("stateid"));
								st.setId(id);
								st.setCitycode(citycode);
								st.setCityname(cityname);
								st.setCitynumber(citynumber);
								st.setCountryid(countryid);
								st.setRegionid(regionid);
								st.setStateid(stateid);
								lstTown.add(st);
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					}
					QuoteTown nullTown = new QuoteTown();
					nullTown.setCitycode("");
					nullTown.setCityname("None");
					nullTown.setCitynumber("");
					nullTown.setCountryid(0);
					nullTown.setId(0);
					nullTown.setRegionid(0);
					nullTown.setStateid(0);
					lstTown.add(0, nullTown);
					ArrayAdapter<QuoteTown> adap = new ArrayAdapter<QuoteTown>(
							PostRequest.this,
							android.R.layout.simple_spinner_item, lstTown);
					adap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					spnTown.setAdapter(adap);
					// spnRegion.setAdapter(adap);

				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});
		// spnRegion.setOnItemSelectedListener(new OnItemSelectedListener() {
		//
		// @Override
		// public void onItemSelected(AdapterView<?> arg0, View arg1,
		// int arg2, long arg3) {
		// selectedRegion = (QuoteRegion) arg0.getItemAtPosition(arg2);
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// });

		spnTown.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				selectedTown = (QuoteTown) arg0.getItemAtPosition(arg2);

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});

		txtFrom.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(FROM_DATE_INPUT_DIALOG);
			}
		});
		txtTo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(TO_DATE_INPUT_DIALOG);
			}

		});

		btnPostRequest.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String message = parseInfo();
				if (message.length() > 0) {
					adstn.dialoglib.Dialog.showToast(getApplicationContext(),
							message);
				} else {
					Map<String, Object> para = new HashMap<String, Object>();
					para.put(QuoteRequest.USERID, WebserviceUtils.getUser()
							.getId());
					para.put(QuoteRequest.ADULT, currentRequest.getAdult());
					para.put(QuoteRequest.CHILDREN,
							currentRequest.getChildren());
					para.put(QuoteRequest.FROM, DateUtils.quoteDateFormat
							.format(currentRequest.getFrom()));
					para.put(QuoteRequest.TO, DateUtils.quoteDateFormat
							.format(currentRequest.getTo()));
					para.put(QuoteRequest.COUNTRYID,
							currentRequest.getCountry());
					para.put(QuoteRequest.STATEID, currentRequest.getState());
					para.put(QuoteRequest.REGION, currentRequest.getRegion());
					para.put(QuoteRequest.TOWN, currentRequest.getTown());
					Object objRs = WebserviceUtils.call("com_xmlrpc",
							"postRequest", para);
					boolean response = (Boolean) objRs;
					if (response) {
						adstn.dialoglib.Dialog.showToast(
								getApplicationContext(),
								"Your request post success");
						setResult(RESULT_OK);
						finish();
					} else {
						PostRequest.this.message = "Post request fail.";
						showDialog(FAIL_REPORT);
					}
				}
			}

		});
		// txtChildren.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// showDialog(DATE_INPUT_DIALOG);
		// txtChildren
		// .setText(DateUtils.pickedDate != null ? DateUtils.pickedDate
		// .toString() : "");
		// }
		//
		// });
		// btnPostRequest.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // Date d=txtChildren.get
		// }
		//
		// });

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		switch (id) {
		case FROM_DATE_INPUT_DIALOG:
			return new DatePickerDialog(this, fromDatePickerListener, year,
					month, day);
		case TO_DATE_INPUT_DIALOG:
			return new DatePickerDialog(this, toDatePickerListener, year,
					month, day);
		case FAIL_REPORT:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(message);
			builder.setNeutralButton("OK",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.dismiss();
						}
					});
			return builder.create();

		default:
			return null;
		}
	}

	// Colect info from input form
	private String parseInfo() {
		String message = "";
		currentRequest = new QuoteRequest();
		int adult = 0;
		try {
			adult = txtAdult.getText().length() > 0 ? Integer.parseInt(txtAdult
					.getText().toString()) : 0;

		} catch (Exception e) {
			return "Number adult must be a number.";
		}
		int children = 0;
		try {
			children = txtChildren.getText().length() > 0 ? Integer
					.parseInt(txtChildren.getText().toString()) : 0;
		} catch (Exception e) {
			return "Number children must be a number.";
		}
		if (adult == 0 && children == 0) {
			return "Sum of adult and children must be less than 1.";
		}
		if (pickedFromDate == null) {
			return "Please select start date.";
		}
		if (pickedToDate == null) {
			return "Please select end date";
		}
		if (pickedFromDate.compareTo(pickedToDate) > 0) {
			return "Start date must be early than end date.";
		}
		if (selectedCountry == null) {
			return "Please select a country.";
		}

		currentRequest.setAdult(adult);
		currentRequest.setChildren(children);
		currentRequest.setFrom(pickedFromDate);
		currentRequest.setTo(pickedToDate);
		currentRequest.setCountry(selectedCountry.getId());
		currentRequest.setState(selectedState != null ? selectedState.getId()
				: 0);
		currentRequest.setTown(String
				.valueOf(selectedTown != null ? selectedTown.getId() : 0));
		currentRequest.setRegion(selectedTown != null ? String
				.valueOf(selectedTown.getRegionid()) : "");
		return message;
	}
}
